﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.IO.IsolatedStorage;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Tasks;

namespace TodayHumor
{
    public partial class Start : PhoneApplicationPage
    {
        SettingsModule settings = new SettingsModule(); 
        BoardLoader BoardLoader = new BoardLoader();

        public Start()
        {
            InitializeComponent();

            // 테마가 '밝게'인지 '어둡게'인지 확인 작업
            PhoneApplicationService.Current.State["IsLightTheme"] = (Visibility)Resources["PhoneLightThemeVisibility"] == Visibility.Visible;
        }

        protected override async void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            // BoardList를 로드하고
            Utilities.GeneratePI(this, "게시판 목록을 로드하고 있습니다..");
            BoardLoader.Load();

            // BoardListListBox에 Binding 해 준다.
            BoardListListBox.ItemsSource = BoardLoader.Boards;
            SystemTray.SetProgressIndicator(this, null);

            // 열람 기록을 로드하고
            Utilities.GeneratePI(this, "열람 기록을 로드하고 있습니다..");
            App.Current.HistoryLoader.Load();

            // HistoryMultiSelectList에 Binding 해 준다.
            HistoryMultiSelectList.ItemsSource = App.Current.HistoryLoader.Articles;
            SystemTray.SetProgressIndicator(this, null);

            // 로그인이 안 되어 있으면 로그인하고
            if (settings.AutoLogin && App.Current.LoginModule.Status == LoginModule.State.NotLoggedIn)
            {
                Utilities.GeneratePI(this, "로그인하고 있습니다..");
                await App.Current.LoginModule.Login(settings.LoginId, settings.LoginPw, settings.AutoLogin);
                SystemTray.SetProgressIndicator(this, null);
            }

            // 현재 밝은 테마로 설정되어 있으면
            if ((bool)PhoneApplicationService.Current.State["IsLightTheme"])
            {
                // 파노라마의 회색을 밝은 회색으로 바꿔준다.
                panorama.Background = new SolidColorBrush(Color.FromArgb(255, 228, 228, 228));
            }

            // 로그인 정보가 바뀌는 이벤트를 연결해 준다.
            App.Current.LoginModule.PropertyChanged += LoginModule_PropertyChanged;

            base.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            // Hit 수 저장을 위해서
            BoardLoader.Save();

            // 로그인 정보가 바뀌는 이벤트 연결을 해제한다.
            App.Current.LoginModule.PropertyChanged += LoginModule_PropertyChanged;
            
            base.OnNavigatedFrom(e);
        }

        #region UI 이벤트 핸들러
        private void SearchTextBoxDeleteButtonClick(object sender, EventArgs e)
        {
            SearchTextBox.Text = String.Empty; SearchTextBox.Focus();
        }

        private void BoardListTextBlockTap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (BoardListListBox.SelectedItem != null)
            {
                // 해당 선택된 SelectedItem의 Hit를 1 올려준다.
                ((Board)BoardListListBox.SelectedItem).Hit++;

                // 선택된 Board를 State를 통해 전송한다.
                PhoneApplicationService.Current.State["SelectedBoard"] = (Board)BoardListListBox.SelectedItem;
                NavigationService.Navigate(new Uri("/Page/Read.xaml", UriKind.Relative));

                // 다시 돌아왔을 때 Board가 선택되어 있을 문제를 해결하기 위해
                BoardListListBox.SelectedItem = null;
            }
        }

        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Page/Login.xaml", UriKind.Relative));
        }

        private void SearchTextBoxTextChanged(object sender, TextChangedEventArgs e)
        {
            // 입력 시 색이 매우 연하게 바뀌는 문제 해결
            if (!string.IsNullOrEmpty(SearchTextBox.Text))
            {
                Brush foregroundBrush = (Brush)Application.Current.Resources["PhoneTextBoxForegroundBrush"];
                if (SearchTextBox.Foreground != foregroundBrush)
                    SearchTextBox.Foreground = foregroundBrush;
            }

            // 넘어온 text가 null이면 전체 Board를 Binding해 준다.
            if (String.IsNullOrEmpty(SearchTextBox.Text))
            {
                BoardListListBox.ItemsSource = BoardLoader.Boards;
            }
            else
            {
                // 아니면 검색 결과를 Binding해 준다.
                BoardListListBox.ItemsSource = BoardLoader.Search(SearchTextBox.Text);
            }
        }

        // 애플리케이션 바 버튼
        ApplicationBarIconButton RefreshBtn = new ApplicationBarIconButton
        {
            IconUri = new Uri("/Images/Icons/refresh.png", UriKind.Relative),
            Text = "새로 고침"
        };
        ApplicationBarIconButton LoginBtn = new ApplicationBarIconButton
        {
            IconUri = new Uri("/Images/Icons/key.png", UriKind.Relative),
            Text = "로그인"
        };
        ApplicationBarIconButton LogoutBtn = new ApplicationBarIconButton
        {
            IconUri = new Uri("/Images/Icons/leave.png", UriKind.Relative),
            Text = "로그아웃"
        };
        ApplicationBarIconButton SettingsBtn = new ApplicationBarIconButton
        {
            IconUri = new Uri("/Images/Icons/settings.png", UriKind.Relative),
            Text = "설정"
        };


        private void PanoramaSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ApplicationBarIconButton LoginOrLogoutBtn = App.Current.LoginModule.Status == LoginModule.State.LoggedIn ? LogoutBtn : LoginBtn;

            switch (panorama.SelectedIndex)
            {
                // 게시판 목록
                case 0:
                    Utilities.SetApplicationBarButtons(ApplicationBar, LoginOrLogoutBtn, RefreshBtn, SettingsBtn);
                    break;
                case 1:
                    break;
            }
        }

        private void HistoryStackPanelTap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            Article SelectedArticle = (sender as StackPanel).DataContext as Article;

            PhoneApplicationService.Current.State["ReadUri"] = true;
            PhoneApplicationService.Current.State["SelectedArticle"] = SelectedArticle;

            NavigationService.Navigate(new Uri("/Page/Read.xaml", UriKind.Relative));
        }

        private void HistoryMenuItemTap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            Article SelectedArticle = (sender as MenuItem).DataContext as Article;

            App.Current.HistoryLoader.Remove(SelectedArticle);
        }
        #endregion

        #region Module 이벤트 핸들러
        void LoginModule_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (App.Current.LoginModule.Status == LoginModule.State.LoggedIn)
            {
                ApplicationBar.Buttons[0] = LogoutBtn;
            }
            else
            {
                ApplicationBar.Buttons[0] = LoginBtn;
            }
        }
        #endregion
    }
}